//
//  ZLDownloaderImageView+LoadingView.swift
//  ZLKit_Swift
//
//  Created by iOS on 2022/8/5.
//

import Foundation
import SnapKit

extension ZLDownloaderImageView {
    
    class LoadingView: UIView {
                
        var state: AccreteDownloader.LoadingState = .normal {
            didSet {
                isHidden = true
                boxView.isHidden = true
                failureView.isHidden = true
                if state == .loading {
                    isHidden = false
                    boxView.isHidden = false
                    return
                }
                if state == .failure {
                    isHidden = false
                    failureView.isHidden = false
                    return
                }
            }
        }
        
        var tryAction: Basic_void = nil
        
        public lazy var contentView: UIView = {
            let view = UIView()
            return view
        }()
        
        public lazy var boxView: LoadingBoxView = {
            let view = LoadingBoxView(progressWidth: progressWidth, progressColor: progressColor)
            return view
        }()
        
        public lazy var failureView: LoadingFailureView = {
            let view = LoadingFailureView()
            view.isUserInteractionEnabled = true
            view.addTarget(self, action: #selector(failureViewAction), for: .touchUpInside)
            return view
        }()
        
        private let loadingSize: CGFloat
        private let progressWidth: CGFloat
        private let progressColor: UIColor
        public init(loadingSize: CGFloat, progressWidth: CGFloat, progressColor: UIColor) {
            self.loadingSize = loadingSize
            self.progressWidth = progressWidth
            self.progressColor = progressColor
            super.init(frame: .zero)
            backgroundColor = .black.withAlphaComponent(0.3)
            addSubview(contentView)
            contentView.snp.makeConstraints({
                $0.center.equalToSuperview()
                $0.size.equalTo(loadingSize)
            })
            contentView.addSubview(boxView)
            boxView.snp.makeConstraints({
                $0.edges.equalToSuperview()
            })
            contentView.addSubview(failureView)
            failureView.snp.makeConstraints({
                $0.edges.equalToSuperview()
            })
        }
        
        required public init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        @objc func failureViewAction() {
            tryAction?()
        }
        
    }
    
}

extension ZLDownloaderImageView.LoadingView {
    
    class LoadingBoxView: UIView {
        
        // 灰色静态圆环
        private let staticLayer: CAShapeLayer = .init()
        // 进度可变圆环
        private let arcLayer: CAShapeLayer = .init()
        
        // 为了显示更精细，进度范围设置为 0 ~ 1
        var progress: Float = 0 {
            didSet {
                setNeedsDisplay()
            }
        }

        private let progressWidth: CGFloat
        private let progressColor: UIColor
        public init(progressWidth: CGFloat, progressColor: UIColor) {
            self.progressWidth = progressWidth
            self.progressColor = progressColor
            super.init(frame: .zero)
            layer.addSublayer(staticLayer)
            layer.addSublayer(arcLayer)
        }

        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            staticLayer.frame = bounds
            update(layer: staticLayer, progress: 1.0, color: .lightGray)
        }
        
        override func draw(_ rect: CGRect) {
            update(layer: arcLayer, progress: progress, color: progressColor)
        }
        
        private func update(layer: CAShapeLayer, progress: Float, color: UIColor) {
            let endAngle = -CGFloat.pi / 2 + (CGFloat.pi * 2) * CGFloat(progress)
            layer.lineWidth = progressWidth
            layer.strokeColor = color.cgColor
            layer.fillColor = UIColor.clear.cgColor
            let radius = self.bounds.width / 2 - layer.lineWidth
            let path = UIBezierPath.init(arcCenter: CGPoint(x: bounds.width / 2, y: bounds.height / 2), radius: radius, startAngle: -CGFloat.pi / 2, endAngle: endAngle, clockwise: true)
            layer.path = path.cgPath
        }
        
    }
    
}

extension ZLDownloaderImageView.LoadingView {
    
    class LoadingFailureView: UIButton {
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            backgroundColor = .red.withAlphaComponent(0.5)
            layer.masksToBounds = true
            setTitleColor(.white, for: .normal)
            contentHorizontalAlignment = .center
            setTitle("!", for: .normal)
        }

        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            layer.cornerRadius = height / 2.0
            titleLabel?.font = .boldSystemFont(ofSize: height / 3.0 * 2.0)
        }
        
    }
    
}
